package com.efounder.pansoft.chat.photo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import androidx.core.app.ActivityCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.core.view.ViewCompat;
import androidx.viewpager.widget.ViewPager;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.efounder.chat.R;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.view.HackyViewPager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.imageselector.photoview.PhotoView;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.FileUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.LinkedList;

import static com.efounder.pansoft.chat.photo.JFPicturePickPhotoWallActivity.SELECTED_VIDEO;
import static com.efounder.pansoft.chat.photo.JFPicturePickPhotoWallActivity.showRawPic;

/**
 * Created by will on 18-4-13.
 * 照片选择组件，预览图片
 * @author wang
 */

public class JFPicturePickBigPictureActivity extends BaseActivity implements View.OnClickListener{

    private TextView tvRawPic, tvSend, tvNumber, tvNumberOf;
    private CheckBox cbRawPic;
    private ArrayList<SelectModel> urls = new ArrayList<>();
    ViewPager mViewPager;
    private int firstPosition = 0;
    private SamplePagerAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_big_picture_pick);
        // 延迟共享动画的执行
        ActivityCompat.postponeEnterTransition(this);

        tvRawPic = (TextView) findViewById(R.id.tv_raw_pic);
        tvSend = (TextView) findViewById(R.id.tv_send_pic);
        cbRawPic = (CheckBox) findViewById(R.id.cb_raw_pic);
        if (!showRawPic){
            cbRawPic.setVisibility(View.INVISIBLE);
            tvRawPic.setVisibility(View.INVISIBLE);
        }
        tvNumber = (TextView) findViewById(R.id.tv_number);
        tvNumberOf = (TextView) findViewById(R.id.tv_numberOf);
        tvNumber.setOnClickListener(this);
        tvRawPic.setOnClickListener(this);
        tvSend.setOnClickListener(this);
        cbRawPic.setOnClickListener(this);

        cbRawPic.setChecked(EnvironmentVariable.getProperty("picture_pick_is_raw_pic","false").equals("true"));
        if (cbRawPic.isChecked()) {
            setupRawPic();
        }
        mViewPager = (HackyViewPager) findViewById(R.id.view_pager);

        if (getIntent().getExtras()!=null && getIntent().getExtras().get("selectedPreview")!=null){
            urls.clear();
            urls.addAll(JFPicturePickPhotoWallActivity.selectedPics);
            firstPosition = getIntent().getIntExtra("curIndex", 0);
            initViewPager();
//        }else if (getIntent().getExtras().containsKey("folderList")) {
//            urls.clear();
//            urls.addAll((ArrayList<SelectModel>)getIntent().getExtras().get("folderList"));
//        }else {
//            urls = JFMessagePicturePickView.getAllPicture(this, -1);
//            firstPosition = getIntent().getIntExtra("curIndex", 0);
        }

        setupButton();

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tvNumberOf.setText(position+1+"/"+urls.size());
                int index = JFPicturePickPhotoWallActivity.selectedPics.indexOf(urls.get(position));
                if (index == -1){
                    tvNumber.setText("");
                    tvNumber.setBackground(getResources().getDrawable(R.drawable.jf_circle_no_number_bg));
                }else {
                    tvNumber.setText(index+1+"");
                    tvNumber.setBackground(getResources().getDrawable(R.drawable.qq_style_circle_number_bg));
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        cbRawPic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setupRawPic();
            }
        });

        EventBus.getDefault().register(this);
    }

    private void initViewPager() {
        adapter = new SamplePagerAdapter(this, urls);
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(firstPosition);
        mViewPager.setPageMargin((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, this.getResources().getDisplayMetrics()));
        tvNumberOf.setText(firstPosition+1+"/"+urls.size());
        int index = JFPicturePickPhotoWallActivity.selectedPics.indexOf(urls.get(firstPosition));
        if (index == -1){
            tvNumber.setText("");
            tvNumber.setBackground(getResources().getDrawable(R.drawable.jf_circle_no_number_bg));
        }else {
            tvNumber.setText(index+1+"");
            tvNumber.setBackground(getResources().getDrawable(R.drawable.qq_style_circle_number_bg));
        }
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEvent(ShowBigPictureEvent showBigPictureEvent) {
        ShowBigPictureEvent stickyEvent = EventBus.getDefault().removeStickyEvent(ShowBigPictureEvent.class);
        // Better check that an event was actually posted before
        if(stickyEvent != null) {
            // Now do something with it
            urls.clear();
            urls.addAll(showBigPictureEvent.getmFiles());
            firstPosition = showBigPictureEvent.getPosition();
            mViewPager = (HackyViewPager) findViewById(R.id.view_pager);
            initViewPager();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_number) {
            int curPosition = mViewPager.getCurrentItem();
            setupNumIndicator(curPosition);
            setupRawPic();
            setupButton();

        } else if (id == R.id.tv_raw_pic) {
            cbRawPic.setChecked(!cbRawPic.isChecked());
            EnvironmentVariable.setProperty("picture_pick_is_raw_pic", String.valueOf(cbRawPic.isChecked()));
        } else if (id == R.id.tv_send_pic) {
            Intent intent = new Intent();
            if (JFPicturePickPhotoWallActivity.selectedPics.size() == 0) {
                SelectModel selectModel = urls.get(mViewPager.getCurrentItem());
                if (selectModel.getType() == MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) {
                    ArrayList<String> tempList = new ArrayList<>();
                    tempList.add(selectModel.getPath());
                    intent.putExtra("mSelectedPics", tempList);
                    intent.putExtra("isRawPic", cbRawPic.isChecked());
                }else {
                    intent.putExtra(SELECTED_VIDEO, selectModel.getPath());
                }
            } else {
                ArrayList<String> tempList = new ArrayList<>();
                for (int i = 0; i < JFPicturePickPhotoWallActivity.selectedPics.size(); i++) {
                    tempList.add(JFPicturePickPhotoWallActivity.selectedPics.get(i).getPath());
                }
                intent.putExtra("mSelectedPics", tempList);
                intent.putExtra("isRawPic", cbRawPic.isChecked());
            }
            setResult(RESULT_OK, intent);
            finish();
            EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");
        }
    }

    public class SamplePagerAdapter extends PagerAdapter {

        private Context context;
        private ArrayList<SelectModel> urls;

        public SamplePagerAdapter(Context context, ArrayList<SelectModel> urls) {
            this.context = context;
            this.urls = urls;
        }

        @Override
        public int getCount() {
            return urls.size();
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            PhotoView photoView = new PhotoView(container.getContext());
            if (position == firstPosition) {
                ViewCompat.setTransitionName(photoView, "imageItem");
                scheduleStartPostponedTransition(photoView);
            }

            LXGlideImageLoader.getInstance().displayImage(context,photoView,urls.get(position).getPath(),R.drawable.loading_image_background);
            // Now just add PhotoView to ViewPager and return it
            container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            if (urls.get(position).getType() == MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) {

            }else {
                ImageView imageView = new ImageView(context);
                imageView.setImageDrawable(getResources().getDrawable(R.drawable.vedio_bg));
                container.addView(imageView);
            }

            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    //共享元素动画延时执行
    private void scheduleStartPostponedTransition(final View sharedElement) {
        sharedElement.getViewTreeObserver().addOnPreDrawListener(
                new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        //启动动画
                        sharedElement.getViewTreeObserver().removeOnPreDrawListener(this);
                        ActivityCompat.startPostponedEnterTransition(JFPicturePickBigPictureActivity.this);
                        return true;
                    }
                });
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ActivityCompat.finishAfterTransition(this);
        //finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Glide.get(this).clearMemory();
        EventBus.getDefault().unregister(this);
    }

    /**
     *设置选择序号
     */
    private void setupNumIndicator(int position) {
        if (urls.get(position).getType() == MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) {
            int index = JFPicturePickPhotoWallActivity.selectedPics.indexOf(urls.get(position));
            if (index == -1) {//不存在则加入数组里
                if (JFPicturePickPhotoWallActivity.maxNum != 0 &&
                        JFPicturePickPhotoWallActivity.selectedPics.size() >= JFPicturePickPhotoWallActivity.maxNum) {
                    ToastUtils.showShort(String.format(ResStringUtil.getString(R.string.bga_pp_toast_photo_picker_max),
                            JFPicturePickPhotoWallActivity.maxNum));
                    return;
                }
                JFPicturePickPhotoWallActivity.selectedPics.add(urls.get(position));
                tvNumber.setText(JFPicturePickPhotoWallActivity.selectedPics.size() + "");
                tvNumber.setBackground(getResources().getDrawable(R.drawable.qq_style_circle_number_bg));
            } else {
                JFPicturePickPhotoWallActivity.selectedPics.remove(index);
                tvNumber.setText("");
                tvNumber.setBackground(getResources().getDrawable(R.drawable.jf_circle_no_number_bg));
            }
        } else {
            if (JFPicturePickPhotoWallActivity.selectedPics.size() == 0) {
                Intent intent = new Intent();
                SelectModel selectModel = urls.get(position);
                intent.putExtra(SELECTED_VIDEO, selectModel.getPath());
                setResult(RESULT_OK, intent);
                finish();
                EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");
                return;
            }
            ToastUtils.showShort(R.string.wechatview_image_video_not_selected);
        }
    }

    /**
     * 设置原图按钮
     */
    private void setupRawPic() {
        tvRawPic.setTextColor(getResources().getColor(R.color.chat_red));
        if (cbRawPic.isChecked()) {
            if (JFPicturePickPhotoWallActivity.selectedPics.size() > 0) {
                LinkedList<String> tempList = new LinkedList<>();
                for (int i = 0; i < JFPicturePickPhotoWallActivity.selectedPics.size(); i++) {
                    tempList.add(JFPicturePickPhotoWallActivity.selectedPics.get(i).getPath());
                }
                String size = FileUtils.getFilesSize(tempList);
                tvRawPic.setText(ResStringUtil.getString(R.string.common_text_raw_pic) + "(" + size + ")");
            }else {
                tvRawPic.setText(R.string.common_text_raw_pic);
            }
        } else {
            tvRawPic.setTextColor(getResources().getColor(R.color.white));
            tvRawPic.setText(R.string.common_text_raw_pic);
        }
    }
    /**
     * 设置确定按钮
     */
    private void setupButton() {
        if (JFPicturePickPhotoWallActivity.selectedPics.size() > 0) {
            tvSend.setText(ResStringUtil.getString(R.string.common_text_confirm) + "(" + JFPicturePickPhotoWallActivity.selectedPics.size() + ")");

        } else {
            tvSend.setText(R.string.common_text_confirm);

        }
    }
}

